<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryMutliAPI, getHomeHotMutliAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref, watch } from 'vue'
import type { CategoryItem, BannerItem, HotItem } from '@/types/home'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  // console.log(res)
  bannerList.value = res.result
}

// 获取前台分类的数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryMutliData = async () => {
  const res = await getHomeCategoryMutliAPI()
  categoryList.value = res.result
}

// 获取热门推荐的数据
const hotList = ref<HotItem[]>([])
const getHomeHotMutliData = async () => {
  const res = await getHomeHotMutliAPI()
  hotList.value = res.result
}

// 是否加载中标记
const isLoading = ref(false)

// 页面加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryMutliData(), getHomeHotMutliData()])
  isLoading.value = false
})

// 猜你喜欢组合式函数调用
const { scrollY, guessRef, onScrolltolower } = useGuessList()

// 当前下拉刷新的状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 加载数据
  // await getHomeBannerData()
  // await getHomeCategoryMutliData()
  // await getHomeHotMutliData()
  // 重置猜你喜欢组件的数据
  guessRef.value?.resetData()
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryMutliData(), getHomeHotMutliData(), guessRef.value?.getMore()])
  // 关闭动画
  isTriggered.value = false
  isLoading.value = false
}

// 侦听请求变化
watch(
  () => guessRef.value?.isSending,
  (state) => {
    if (state) {
      uni.showLoading({ title: '加载中~', mask: true })
    } else {
      uni.hideLoading()
    }
  }
)
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view refresher-enabled @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered" @scrolltolower="onScrolltolower" class="scroll-view" :scroll-y="scrollY">
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
/* #ifdef APP-PLUS */
#app,
/* #endif */
page {
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
  height: 100%;

  .scroll-view {
    flex: 1;
  }
}
</style>
